package com.javaweb.cwj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.cwj.entity.EduChapter;
import com.javaweb.cwj.entity.EduVideo;
import com.javaweb.cwj.entity.chapter.chapterVo;
import com.javaweb.cwj.entity.chapter.videoVo;
import com.javaweb.cwj.exception.cwjException;
import com.javaweb.cwj.mapper.EduChapterMapper;
import com.javaweb.cwj.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javaweb.cwj.service.EduVideoService;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-05-13
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
@Autowired
private EduVideoService eduVideoService;
    @Override
    public List<chapterVo> findChapterBycourseId(String courseId) {
        //根据id查出所有的章节
        QueryWrapper queryWrapper = new QueryWrapper();
         queryWrapper.eq("course_id",courseId);
        List<EduChapter>eduChapterList= baseMapper.selectList(queryWrapper);
        //根据id查询出所有的video
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper.eq("course_id",courseId);
        List<EduVideo>eduVideoList =  eduVideoService.list(queryWrapper1);
        //遍历所有的章节
        List<chapterVo> finalChapter = new ArrayList<>();
        for (int i = 0; i <eduChapterList.size() ; i++) {
            EduChapter eduChapter = eduChapterList.get(i);
            chapterVo chapterVo = new chapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);
            finalChapter.add(chapterVo);

            //遍历所有的video 把video添加到对应的章节里面去
            List<videoVo> videoVoList = new ArrayList<>();
            for (int m = 0; m < eduVideoList.size(); m++) {
                EduVideo eduVideo = eduVideoList.get(m);
                if (eduChapter.getId().equals(eduVideo.getChapterId())) {
                    videoVo videoVo = new videoVo();
                    BeanUtils.copyProperties(eduVideo, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        return finalChapter;
    }

    @Override
    public int deleteChapter(String chapterId) {
        //查询章节下面出是否有小节
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("chapter_id",chapterId);

        int count  = eduVideoService.count(queryWrapper);
        if(count>0){
            throw new cwjException(200001,"章节下面有小节 不能删除");
        }else{
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("id",chapterId);
           int i  =  baseMapper.delete(queryWrapper1);
            return i;
        }

    }
}
